package com.qsmx.core.webfile.client;

import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Handler;
import android.webkit.CookieManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;

import com.qsmx.core.app.Atmos;
import com.qsmx.core.app.ConfigKeys;
import com.qsmx.core.util.storage.AtmosPreference;
import com.qsmx.core.webfile.FileWebViewClient;
import com.qsmx.core.webfile.IPageLoadListener;
import com.qsmx.core.webfile.WebDelegate;

/**
 * @ClassName: WebViewClientImpl
 * @Description: java类作用描述
 * @Author: Jove.Nan
 * @Date: 2019/3/22 5:17 PM
 */
public class WebViewClientImpl extends FileWebViewClient {

    private final WebDelegate DELEGATE;
    private IPageLoadListener mIPageLoadListener = null;
    private static final Handler HANDLER = Atmos.getHandler();

    public void setPageLoadListener(IPageLoadListener listener) {
        this.mIPageLoadListener = listener;
    }

    public WebViewClientImpl(WebDelegate delegate) {
        this.DELEGATE = delegate;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
//        AtmosLogger.d("shouldOverrideUrlLoading", url);
//        return Router.getInstance().handleWebUrl(DELEGATE, url);
        if (Build.VERSION.SDK_INT < 26) {
            view.loadUrl(url);
            return true;
        }
        return false;
    }

    private void syncCookie() {
        final CookieManager manager = CookieManager.getInstance();
        /**
         * 注意，这里的cookie和API请求的Cookie是不一样的，这个在网页不可见
         */
        final String webHost = Atmos.getConfiguration(ConfigKeys.WEB_HOST);
        if (webHost != null) {
            if (manager.hasCookies()) {
                final String cookieStr = manager.getCookie(webHost);
                if (cookieStr != null && cookieStr.equals("")) {
                    AtmosPreference.addCustomAppProfile("cookie", cookieStr);
                }
            }
        }
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);

        if (mIPageLoadListener != null) {
            mIPageLoadListener.onLoadStart();
        }
//        AtmosLoader.showLoading(view.getContext());
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        syncCookie();
        if (mIPageLoadListener != null) {
            mIPageLoadListener.onLoadEnd();
        }
//        AtmosLoader.stopLoading();
    }

    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        handler.proceed(); //解决方案在此，不要调用super.xxxx
    }
}
